#include "PeerContainer.h"

#include "Trash.h"
#include "Peer.h"
#include "MyAssert.h"
#include "OSMutex.h"

CPeerContainer::CPeerContainer()
{
}


CPeerContainer::~CPeerContainer()
{
	while(!m_PeersList.empty())
	{
		delete m_PeersList.begin()->second;
		m_PeersList.erase(m_PeersList.begin());
	}
}

/**
 * 
 * @param pPeer 
 * @return 
 */
Int32 CPeerContainer::AddPeer(CPeer * pPeer)
{
	Assert(pPeer);
	if(!pPeer)
		return OS_Err;

	OSMutexLocker locker(&m_Mutex);
	_PeerMapIterator it = m_PeersList.find(pPeer->GetPeerInfo()->GetPeerID());
	if(it == m_PeersList.end())
	{
		m_PeersList[pPeer->GetPeerInfo()->GetPeerID()] = pPeer;
		return OS_NoErr;
	}
	return OS_Err;
	
}

Int32 CPeerContainer::DelPeer(PEERID vID)
{
	OSMutexLocker locker(&m_Mutex);
	_PeerMapIterator it = m_PeersList.find(vID);
	if(it != m_PeersList.end())
	{
		CPeer *pPeer = it->second;
		m_PeersList.erase(it);
		delete pPeer;		
		return OS_NoErr;
	}
	return OS_Err;
}

CPeer* CPeerContainer::FindPeer(PEERID vID)
{
	CPeer *pPeer = NULL;
	OSMutexLocker locker(&m_Mutex);

	_PeerMapIterator it = m_PeersList.find(vID);
	if(it != m_PeersList.end())
		pPeer = it->second;
	return pPeer;
}

Bool CPeerContainer::FindPeer(CPeer *pPeer)
{
	if(pPeer == NULL)
		return FALSE;

	OSMutexLocker locker(&m_Mutex);
	
	_PeerMapIterator it = m_PeersList.find(pPeer->GetPeerID());
	if(it == m_PeersList.end())
		return FALSE;

	return TRUE;
}

CPeer* CPeerContainer::AllocatePeer()
{
	return new CPeer;
}

void CPeerContainer::ReclaimPeer(CPeer *pPeer)
{
	if(pPeer)
		delete pPeer;
}

UInt32 CPeerContainer::GetPeerCount()
{
	m_Mutex.Lock();
	UInt32 iCount = m_PeersList.size();
	m_Mutex.Unlock();
	return iCount;
}
